<?php
/**
 * Created by JetBrains PhpStorm.
 * User: thanhnv
 * Date: 19/11/12
 * Time: 8:50 PM
 * To change this template use File | Settings | File Templates.
 */
namespace Admin\Controller;

use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Exception;
use Logger;
use Model\UserTable;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Zend\Json\Json;


class UserController extends AdminBaseController
{
    public function indexAction()
    {
        $roleTable = $this->getTableFinder()->getRoleTable();
        $viewModel = new ViewModel();
        $viewModel->setVariable('allRole', $roleTable->getAll());

        return $viewModel;
    }

    public function userInfoAction()
    {
        $roleTable = $this->getTableFinder()->getRoleTable();
        $viewModel = new ViewModel();
        $viewModel->setVariable('allRole', $roleTable->getAll());

        return $viewModel;
    }
    public function addAction()
    {
        try{
            $roleTable = $this->getTableFinder()->getRoleTable();
            return new ViewModel(array('allRole'=> $roleTable->getAll()));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function editAction()
    {
        try{
            $id = $this->params()->fromQuery('id');
            if(!$id) throw new BusinessException("User id null");
            $userTable = $this->getTableFinder()->getUserTable();
            $template = $userTable->getUser($id);

            $roleTable = $this->getTableFinder()->getRoleTable();
            return new ViewModel(array('userItem'=>$template, 'allRole'=> $roleTable->getAll()));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    private function validate($paramArr){
        $userName = $paramArr["username"];
        $name = $paramArr["name"];
        $password = $paramArr["password"];
        $retypePassword = $paramArr["retypedPassword"];

        if(!$paramArr['userId']) {
            if(!$userName || !$name || !$password)
                throw new BusinessException('Vui lòng nhập đầy đủ các thông tin bắt buộc.');
            if($password != $retypePassword)
                throw new BusinessException('Password nhập lại không trùng khớp.');
        }
        else{
            if(!$userName || !$name)
                throw new BusinessException('Vui lòng nhập đầy đủ các thông tin bắt buộc.');
        }

        $user = new UserTable();
        if(!$paramArr['userId']) {
            $user_Item = $user->getUserByName($userName);
            if($user_Item)
                throw new BusinessException('Đã tồn tại người dùng có username là: '.$userName);
        }else{
            $user_Item = $user->getUserByName($userName);
            if($user_Item && $user_Item->id != $paramArr['userId'])
                throw new BusinessException('Đã tồn tại người dùng có username là: '.$userName);
        }
    }

    public function listAction()
    {
        $role = $this->params()->fromPost("role");
        $name = $this->params()->fromPost("name");

        $searchOption = array();
        $searchOption['role'] = $role;
        $searchOption['name'] = $name;

        $sortData = $this->params()->fromPost("sort");
        if($sortData){
            $order = array();
            foreach ($sortData as $sortField) {
                $field = $sortField['field'];
                $direction = $sortField['dir'];
                $orderClause = $field." ".$direction;
                array_push($order, $orderClause);
            }
        }else{
            $order = array("id desc");
        }

        $page = $this->params()->fromPost("page");
        $rows = $this->params()->fromPost("pageSize");
        $offset = ($page - 1) * $rows;

        $userTable = $this->getTableFinder()->getUserTable();
        $result = $userTable->searchUser(true,$offset,$rows,$order,$searchOption);

        return new JsonModel(array(
            'rows' => $result['rows']->toArray(),
            'total' => $result['total'],
            'success'=>true,
        ));

    }

    public function removeAction()
    {
        try{
            $id = $this->params()->fromQuery("id");

            if(!$id){
                throw new BusinessException("Chưa truyền id để xóa người dùng");
            }
            $userTable = $this->getTableFinder()->getUserTable();
            $userItem = $userTable->getUser($id);
            if($userItem->deletable == 0)
                throw new BusinessException("Không thể xóa người dùng: ".$userItem->username);

            $userTable->removeUser($id );
            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            Logger::crit($e->getMessage());
            if($e instanceof BusinessException){
               return new JsonModel(array('msg'=>'Lỗi: '.$e->getMessage()));
            }
            return new JsonModel(array('msg'=>'Lỗi hệ thống. Vui lòng liên hệ admin.'));
        }
    }

    public function saveAction()
    {
        try{
            //$this->validate($this->getAllParams());

            $userId = $this->params()->fromPost("userId");
            $userName = $this->params()->fromPost("username");
            $name = $this->params()->fromPost("name");

            $password = $this->getDigestService()->getUserPassword($userName, $this->params()->fromPost("password"));
            $phone = $this->params()->fromPost("phone");
            $email = $this->params()->fromPost("email");
            $allRole = $this->params()->fromPost("accessRoles");
            $active = $this->params()->fromPost("active");
            $isLog = $this->params()->fromPost("isLog");

            $userTable = $this->getTableFinder()->getUserTable();
            //update
            if($userId){
                $userTable->update(array("id"=>$userId, "name"=>$name, "username" => $userName,
                    "phone_number" => $phone, "email" => $email, "active" => $active, 'is_log'=>$isLog), $userId);
                $userItem = $userTable->getUser($userId);
                $userItem->detachAllRole();
            }else{
                $userId = $userTable->insert(array("name"=>$name, "username" => $userName, "password" => $password,
                    "phone_number" => $phone, "email" => $email, "active" => $active, 'is_log'=>$isLog));
                $userItem = $userTable->getUser($userId);
            }
            if($allRole)
                foreach ($allRole as $roleId) {
                    $userItem->addRole($roleId);
                }
            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            Logger::crit($e->getMessage());
            if($e instanceof BusinessException){
                return new JsonModel(array('msg'=>'Lỗi: '.$e->getMessage()));
            }
            return new JsonModel(array('msg'=>'Lỗi hệ thống. Vui lòng liên hệ admin.'));
        }
    }

    public  function resetPassAction(){
        try{
            $userId = $this->params()->fromPost("userId");

            $userTable = $this->getTableFinder()->getUserTable();
            $userItem = $userTable->getUser($userId);
            $plainPass = CommonHelper::rand_string(8);
            $password = $this->getDigestService()->getUserPassword( $userItem->username,
                $plainPass);

            $userTable->update(array('id'=>$userId, 'password'=>$password), $userId);

            return new JsonModel(array('success'=>true, 'password'=>$plainPass));
        }catch(Exception $e){
            Logger::crit($e->getMessage());
            if($e instanceof BusinessException){
                return new JsonModel(array('msg'=>'Lỗi: '.$e->getMessage()));
            }
            return new JsonModel(array('msg'=>'Lỗi hệ thống. Vui lòng liên hệ admin.'));
        }
    }

    /*


    public function getroleAction()
    {
        try{
            $id = $this->_getParam("id");
            $excludedRoleId = $this->_getParam("excludedRoleId");
            $userService = new User();
            if(!$id)
                throw new Core_Exception_Business("User id không tồn tại");
            $user_Item = $userService->getUserById($id);
            $allRole = $user_Item->getAllRole();
            $tmpArr=array();

            if($excludedRoleId){

                foreach ($allRole->toArray() as $roleItem) {
                    if($roleItem["id"] != $excludedRoleId )
                        array_push($tmpArr, $roleItem);
                }
                $this->_helper->json($tmpArr);
            }

            $this->_helper->json($allRole->toArray());
        }catch(Exception $e){
            Logger::crit($e->getMessage());
            return array();
        }

    }

    public function saveMyInfoAction()
    {
        try{
            $allParams = $this->getAllParams();
            $allParams['userId'] = $this->getUser()->id;
            $this->validate($allParams);

            $userName = $this->_getParam("username");
            $name = $this->_getParam("name");
            $phone = $this->_getParam("phone");
            $email = $this->_getParam("email");

            $userService = new User();

            $userService->updateUser(array("id"=> $allParams['userId'], "name"=>$name, "username" => $userName,
                "phone_number" => $phone, "email" => $email));

            $this->_helper->json(array('success'=>true));
        }catch(Exception $e){
            Logger::crit($e->getMessage());
            if($e instanceof Core_Exception_Business){
                $this->_helper->json(array('msg'=>'Lỗi: '.$e->getMessage()));
            }
            $this->_helper->json(array('msg'=>'Lỗi hệ thống. Vui lòng liên hệ admin.'));
        }

    }*/


}
